<?php

namespace App\V3\V3_2_7\Controllers;

use App\Rules\JsonArray;
use App\Services\CommonService;
use App\V3\V3_2_7\Models\AdminAddendumModel;
use App\V3\V3_2_7\Models\AdminModel;
use App\V3\V3_2_7\Models\SystemConfigModel;
use App\V3\V3_2_7\Models\VipSettingModel;
use App\V3\V3_2_7\Services\AdminService;
use App\V3\V3_2_7\Services\DataFieldService;
use App\V3\V3_2_7\Services\UserMenuService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\V3\V3_2_7\Services\LoginService;
use OSS\OssClient;
use App\Services\MessageService;
use Illuminate\Http\JsonResponse;

class AdminController extends BaseController
{
    protected $ossClient;
    protected $time;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->time = time();
        $this->ossClient = new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint')
        );
    }

    /**
     * 子账号列列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/8 14:42
     * @return \Illuminate\Http\JsonResponse
     */
    public function userList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
            'pageSize.required' => '参数`页面大小`丢失',
            'pageSize.integer' => '参数`页面大小`仅能为数字',
            'currentPage.required' => '参数`当前页码`丢失',
            'currentPage.integer' => '参数`当前页码`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['keyword'] = empty($data['keyword']) ? '' : $data['keyword'];

        return $this->success(
            AdminService::userList($this->getMainUserId(), $data)
        );
    }

    /**
     * 转换子账号状态
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/8 16:14
     * @return \Illuminate\Http\JsonResponse
     */
    public function transStatus(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//用户id
            'is_active' => [
                'required',
                'integer',
                Rule::In([0, 1]),
            ],//状态;1:启用;0:禁用;
        ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
                'is_active.required' => '参数`status`缺失',
                'is_active.integer' => '参数`status`只能为数字',
                'is_active.in' => '参数`status`不合法',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //检查子账户是否存在
        $userInfo = AdminModel::where('id', $data['id'])->first();

        if (!$userInfo) {
            return $this->fail('', '用户不存在');
        }
        if ($data['is_active']) {
            $do = '已启用！';
        } else {
            $do = '已禁用！';
        }
        $logData = '员工账号：' . $userInfo['username'] . $do;
        $this->operateLog('启禁用子账号', $data, $this->time, $logData);
        Redis::SET('user_id_' . $data['id'] . '_disabled', 1);
        AdminModel::where('id', $data['id'])->update(['is_active' => $data['is_active']]);

        CommonService::operateResult($this->getUserId(), $this->time, ['code' => 0, 'msg' => 'success', 'data' => '']);
        return $this->success();
    }

    /**
     * 审批人列表
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/8 16:07
     * @return \Illuminate\Http\JsonResponse
     */
    public function approverList()
    {
        return $this->success(
            AdminService::approverList($this->getMainUserId())
        );
    }

    /**
     * 重置指定子账户登录密码
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/8 16:30
     * @return \Illuminate\Http\JsonResponse
     */
    public function resetPwd(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//用户id
        ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $time = time();
        //检查子账户是否存在
        $userInfo = AdminModel::where('id', $data['id'])->first();
        if (!$userInfo) {
            return $this->fail('', '用户不存在');
        }
        $logData = '员工账号：' . $userInfo['username'] . '密码已更改！';
        $this->operateLog('重置子账号登录密码', $data, $time, $logData);
        AdminService::resetPwd($data, $userInfo);
        CommonService::operateResult($this->getUserId(), $time, ['code' => 0, 'msg' => 'success', 'data' => '']);

        return response()->json(['code' => 0, 'msg' => 'success', 'data' => '']);
    }

    /**
     * 删除指定子账户
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/8 17:27
     * @return \Illuminate\Http\JsonResponse
     */
    public function delUser(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//用户id
        ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为数字',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //检查子账户是否存在
        $userInfo = AdminModel::where('id', $data['id'])->first();
        if (!$userInfo) {
            return $this->fail('', '用户不存在');
        }
        $time = time();
        $logData = '员工账号：' . $userInfo['username'] . '已删除！';
        $this->operateLog('删除子账号', $data, $time, $logData);
        AdminModel::where('id', $data['id'])->update(['delete_flag' => 1]);
        CommonService::operateResult($this->getUserId(), $time, ['code' => 0, 'msg' => 'success', 'data' => '']);
        return $this->success();
    }

    /**
     * 新建子账号
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/9 11:20
     * @return \Illuminate\Http\JsonResponse
     */
    public function addUser(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'username' => 'required',//用户id
//            'nickname' => 'required',//用户id
            // 'mobile' => 'regex:/^1[345789][0-9]{9}$/',
            'is_active' => [
                'required',
                'integer',
                Rule::In([0, 1]),
            ],//状态;1:启用;0:禁用;
        ],
            [
                'username.required' => '参数`账号`缺失',
//                'nickname.required' => '参数`子账号昵称`缺失',
                // 'mobile.regex' => '手机号格式错误，请重试',
//                'is_active.required' => '参数`status`缺失',
//                'is_active.integer' => '参数`status`只能为数字',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $accountNum = AdminModel::where('parent_id', $this->getMainUserId())
            ->where('delete_flag', 0)->count();

        if (!$this->isVip() && $accountNum >= $this->subAccountNumber()) {
            return $this->fail('', '您当前为非VIP用户，最多可创建' . $this->subAccountNumber() . '个子账号');
        }

        if (!empty($data['mobile'])) {
            $checkMobile = Validator::make($data, [
                'mobile' => 'regex:/^1[345789][0-9]{9}$/',
            ],
                [
                    'mobile.regex' => '手机号格式错误，请重试',
                ]
            );

            if ($infos = $checkMobile->errors()->first()) {
                return $this->fail('', $infos);
            }
        }

//        $checkUser = AdminService::checUserInfo($this->getMainUserId(), $data);
//
//        if(!$checkUser) {
//            return $this->fail('', '账号已存在');
//        }

        $logData = '员工账号：' . $data['username'] . ',已创建！';
        $time = time();
        $this->operateLog('新建子账号', $data, $time, $logData);

        $result = AdminService::addUser($this->getMainUserId(), $data, $time);
        CommonService::operateResult($this->getMainUserId(), $time, $result);
        return response()->json(
            $result
        );
    }

    /**
     * 编辑指定子账号信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/9 13:52
     * @return \Illuminate\Http\JsonResponse
     */
    public function editUserInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//用户id
            'username' => 'required',//用户id
//            'nickname' => 'required',//用户id
//            'is_active' => [
//                'required',
//                'integer',
//                Rule::In([0,1]),
//            ],//状态;1:启用;0:禁用;
        ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
                'username.required' => '参数`账号`缺失',
//                'nickname.required' => '参数`子账号昵称`缺失',
//                'is_active.required' => '参数`status`缺失',
//                'is_active.integer' => '参数`status`只能为数字',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if (!empty($data['mobile'])) {
            $checkMobile = Validator::make($data, [
                'mobile' => 'regex:/^1[345789][0-9]{9}$/',
            ],
                [
                    'mobile.regex' => '手机号格式错误，请重试',
                ]
            );

            if ($infos = $checkMobile->errors()->first()) {
                return $this->fail('', $infos);
            }
        }

        $checkUser = AdminModel::where('id', $data['id'])
            ->where('delete_flag', 0)->first();

        if (empty($checkUser)) {
            return $this->fail('', '账号不存在');
        }

//        $data['is_active'] = $data['status'];
        unset($data['status']);

        $randNo = rand(100000, 999999);

        do {
            $randNo = rand(100000, 999999);
        } while (!empty(AdminModel::where('parent_id', '!=', 0)
            ->where([
                'delete_flag' => 0,
                'newpwd' => $randNo
            ])->first()));

        $data['newpwd'] = empty($data['newpwd']) ? $randNo : $data['newpwd'];
        if (strlen($data['newpwd']) < 6) {
            $result = ['code' => 1, 'msg' => '密码最小为6位字符', 'data' => ''];
            CommonService::operateResult($this->getUserId(), $this->time, $result);
            return response()->json($result);
        }
        $logData = '员工账号：' . $checkUser['username'] . '信息已修改！';
        $this->operateLog('修改子账号信息', $data, $this->time, $logData);

        AdminModel::where('id', $data['id'])->update($data);

        $result = ['code' => 0, 'msg' => 'success', 'data' => ''];

        CommonService::operateResult($this->getUserId(), $this->time, $result);

        return response()->json($result);
    }

    /**
     * 设置子账号权限
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/9 15:42
     * @return \Illuminate\Http\JsonResponse
     */
    public function setUser(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//用户id
//            'first_module' => 'required',
            'second_module' => 'required',
            'limit_module_info' => [
                'json',
                new JsonArray([
                    'module_id' => 'required|integer',//模块id
                    'upper_module_id' => 'required|integer|',//模块上一级id
                ])
            ],
        ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
//                'first_module.required' => '参数`一级权限菜单模块`缺失',
                'second_module.required' => '参数`二级权限菜单模块`缺失',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $checkUser = AdminModel::where('id', $data['id'])
            ->where('delete_flag', 0)->first();

        if (empty($checkUser)) {
            return $this->fail('', '账号不存在');
        }
        $time = time();
        $adminData = [];
        $adminData['id'] = $data['id'];
//        $adminData['first_module'] = $data['first_module'];
        $adminData['second_module'] = $data['second_module'];
//        AdminModel::where('id', $data['id'])->update($adminData);
        $adminData['main_id'] = $this->getMainUserId();
        AdminService::setUserPermissions($adminData);
        //Redis::SET('user_id_'.$data['id'].'_reset', 1);
        $logData = '员工账号：' . $checkUser['username'] . '权限已更新！';
        $this->operateLog('修改子账号权限', $data, $time);
        //设置限制参数
        DataFieldService::setFieldPermission($data);
        CommonService::operateResult($this->getUserId(), $time, ['code' => 0, 'msg' => 'success', 'data' => '']);

        return $this->success();
    }

    /**
     * 获取子账号权限信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/9 16:08
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserPermission(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//用户id
        ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $userInfo = AdminModel::where('id', $data['id'])->where('delete_flag', 0)->first();

        if (empty($userInfo)) {
            return $this->fail('', '账号不存在');
        }

//        $this->log('获取子账号可用权限信息', $data);
        return $this->success(AdminService::getUserPermission($this->getMainUserId(), $userInfo));
    }

    /**
     * 修改手机号-主账号
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/9 16:31
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function changeMobile(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'code' => 'required',//验证码
            'mobile' => 'required|regex:/^1[345789][0-9]{9}$/',
        ],
            [
                'code.required' => '参数`验证码`缺失',
                'mobile.required' => '手机号不能为空，请输入手机号',
                'mobile.regex' => '手机号格式错误，请重试',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $this->operateLog('修改手机号-主账号', $data, $this->time);
        if (!$this->getUserTpye()) {
            //比对用户输入的code和短信发送的code是否一致
            if (!Redis::exists($data['mobile'] . '_mobile_login')) {
                CommonService::operateResult($this->getUserId(), $this->time, ['code' => 1, 'msg' => '您输入的验证码无效，请重试', 'data' => '']);
                return ['code' => 1, 'msg' => '您输入的验证码无效，请重试', 'data' => ''];
            } else {
                if ($data['code'] == Redis::get($data['mobile'] . '_mobile_login')) {//验证码一致
                    $checkUserInfo = AdminModel::where('username', $data['mobile'])
                        ->where('parent_id', 0)
                        ->where('delete_flag', 0)
                        ->where('id', '!=', $this->getUserId())->first();

                    if (!empty($checkUserInfo)) {
                        CommonService::operateResult($this->getUserId(), $this->time, ['code' => 1, 'msg' => '手机号已存在，无法重复使用', 'data' => '']);
                        return $this->fail('', '手机号已存在，无法重复使用');
                    } else {

                        AdminModel::changeMobile($this->getUserId(), $data);
                    }

                    Redis::del($data['mobile'] . '_mobile_login');//销毁验证信息
                    CommonService::operateResult($this->getUserId(), $this->time, ['code' => 0, 'msg' => 'success', 'data' => '']);
                    return $this->success();
                } else {
                    CommonService::operateResult($this->getUserId(), $this->time, ['code' => 1, 'msg' => '您输入的验证码有误，请重新输入', 'data' => '']);
                    return $this->fail('', '您输入的验证码有误，请重新输入');
                }
            }
        } else {
            $logData = '主账号已修改为：' . $data['mobile'];
            CommonService::operateResult($this->getUserId(), $this->time, ['code' => 1, 'msg' => '子账号无法完成此操作', 'data' => ''], $logData);
            return $this->fail('', '子账号无法完成此操作');
        }
    }

    /**
     * 修改用户信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/9 17:13
     * @return \Illuminate\Http\JsonResponse
     */
    public function modifyUserinfo(Request $request)
    {
        $data = $request->all();
        if (!empty($logo_img_files = $request->file('company_logo_img'))) {
            $res = self::handlePicFormat($logo_img_files, 'p', '企业LOGO图片，格式不正确！');//判断文件格式
            if (!empty($res)) return $this->fail('', $res['msg']);
            if ($logo_img_files->isValid()) {
                $imgPath = $logo_img_files->store('logo/img/' . date('Y') . '-' . date('m') . '-' . date('d'));
                $imgRes = self::addOssUploadImg($this->ossClient, $this->getMainUserId(), $logo_img_files, $imgPath);
                if ($imgRes['code'] === 0) {
                    $data['company_logo_img'] = $imgRes['data'];
                } else {
                    return $this->fail('', $imgRes['msg']);
                }

            } else {

                return $this->fail('', '企业LOGO图片，上传失败！');
            }
        }
        if (!empty($profile_photo_files = $request->file('profile_photo_img'))) {
            $res = self::handlePicFormat($profile_photo_files, 'p', '头像图片，格式不正确！');//判断文件格式
            if (!empty($res)) return $this->fail('', $res['msg']);
            if ($profile_photo_files->isValid()) {
                $imgPath = $profile_photo_files->store('logo/img/' . date('Y') . '-' . date('m') . '-' . date('d'));
                $imgRes = self::addOssUploadImg($this->ossClient, $this->getMainUserId(), $profile_photo_files, $imgPath);
                if ($imgRes['code'] === 0) {
                    $data['profile_photo_img'] = $imgRes['data'];
                } else {
                    return $this->fail('', $imgRes['msg']);
                }

            } else {
                return $this->fail('', '头像图片，上传失败！');
            }

        }
        $logData = '用户信息已更新！';
        $this->operateLog('修改用户信息', $data, $this->time, $logData);
        AdminModel::where('id', $this->getUserId())->update($data);
        CommonService::operateResult($this->getUserId(), $this->time, ['code' => 0, 'msg' => 'success', 'data' => '']);
        return $this->success();
    }

    /**
     * 子账号修改登录密码
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/10 10:23
     * @return \Illuminate\Http\JsonResponse
     */
    public function changePassword(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'old_pwd' => 'required',//旧密码
            'new_pwd' => 'required|min:6',//新密码
            'confirm_pwd' => 'required',//确认密码
        ],
            [
                'old_pwd.required' => '请输入旧密码',
                'new_pwd.required' => '请输入新密码',
                'new_pwd.min' => '密码最小长度为6位',
                'confirm_pwd.required' => '请输入确认密码',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if ($data['new_pwd'] != $data['confirm_pwd']) {
            return $this->fail('', '两次输入的密码不一致，请重新输入');
        }

        $checkPwd = AdminService::checkPwd($this->getUserId(), $data);

        if (!$checkPwd) {
            return $this->fail('', '旧密码不正确,请重新输入');
        }

        $this->operateLog('子账号修改登录密码', $data, $this->time);

        AdminService::changePwd($this->getUserId(), $data);
        $userInfo = AdminModel::select('username')->where('id', $this->getUserId())->first();
        $logData = '子账号:' . $userInfo['username'] . ' 密码已修改！';
        CommonService::operateResult($this->getUserId(), $this->time, ['code' => 0, 'msg' => 'success', 'data' => ''], $logData);
        return $this->success();
    }

    /**
     * 个人中心
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/10 10:44
     * @return \Illuminate\Http\JsonResponse
     */
    public function userCenter()
    {
        return $this->success(
            AdminService::userCenter(
                $this->getUserId(),
                $this->getMainUserId(),
                $this->getUserTpye()
            )
        );
    }

    /**
     * 解绑微信
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/10 11:01
     * @return \Illuminate\Http\JsonResponse
     */
    public function relieveWechatBind()
    {
        $adminInfo = AdminModel::where('id', $this->getUserId())->first();

        $this->operateLog('解绑微信', $this->getUserId(), $this->time);
        if (!empty($adminInfo['openid'])) {
            AdminModel::where('id', $this->getUserId())->update([
                'openid' => '',
                'wx_nickname' => ''
            ]);
        } else {
            CommonService::operateResult($this->getUserId(), $this->time, ['code' => 1, 'msg' => '您当前还未绑定微信', 'data' => '']);
            return $this->fail('', '您当前还未绑定微信');
        }
        $logData = '解绑微信成功！';
        CommonService::operateResult($this->getUserId(), $this->time, ['code' => 0, 'msg' => 'success', 'data' => ''], $logData);
        return $this->success();
    }

    /**
     * 微信绑定
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/10 11:07
     * @return \Illuminate\Http\JsonResponse
     */
    public function wechatBind(Request $request)
    {
        $adminInfo = AdminModel::where('id', $this->getUserId())->first();

        $wxinfo = json_decode(LoginService::getOpenId($request->code), true);

        $this->operateLog('微信绑定', $this->getUserId(), $this->time);
        if (empty($adminInfo['openid']) && !empty($request->code)) {
            AdminModel::where('id', $this->getUserId())->update([
                'openid' => $wxinfo['openid'],
                'wx_nickname' => $request->nickname
            ]);
        }
        $logData = '微信绑定成功！';
        CommonService::operateResult($this->getUserId(), $this->time, ['code' => 0, 'msg' => 'success', 'data' => ''], $logData);
        return $this->success();
    }

    /**
     * 获取被邀请人列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/10 11:17
     * @return \Illuminate\Http\JsonResponse
     */
    public function inviteList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ],
            [
                'pageSize.required' => '参数`pageSize`缺失',
                'pageSize.integer' => '参数`pageSize`只能为数字',
                'currentPage.required' => '参数`currentPage`缺失',
                'currentPage.integer' => '参数`currentPage`只能为数字',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info, 1);
        }

        if ($this->getUserTpye() == 1) {
            return $this->fail('', '您的权限不足，无法查看被邀请人信息');
        }

        return $this->success(
            AdminService::inviteList(
                $this->getMainUserId(),
                $data
            )
        );
    }

    /**
     * 设置密码
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/14 13:33
     * @return \Illuminate\Http\JsonResponse
     */
    public function setPwd(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'password' => 'required',//页面大小
            'confirm_pwd' => ['required', 'same:password'],//当前页
        ],
            [
                'password.required' => '请输入密码',
                'confirm_pwd.required' => '请输入确认密码',
                'confirm_pwd.same' => '两次密码不一致',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info, 1);
        }

        $data['id'] = $this->getUserId();
        $info = AdminModel::where('id', $data['id'])->first();
        $logData = '账号：' . $info['username'] . '密码已设置';
        $this->operateLog('设置密码', $data, $this->time, $logData);
        AdminService::setPwd($data);
        return $this->success();
    }

    /**
     * 转换出库方式
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/17 13:55
     * @return \Illuminate\Http\JsonResponse
     */
    public function transOutWay()
    {
        return response()->json(
            AdminService::transOutWay($this->getMainUserId())
        );
    }

    /**
     * 是否共享客户
     * AUTHOR  : Sun Wu
     * DateTime: 2022/8/5 18:20
     * @return \Illuminate\Http\JsonResponse
     */
    public function isShareCustomers()
    {
        if ($this->getUserTpye()) {
            return $this->fail('', '当前账号权限不足，无法修改');
        }
        $adminInfo = AdminAddendumModel::where('main_id', $this->getUserId())->first();

        if ($adminInfo->is_share_customer) {
            $status = 0;
            $adminInfo->is_share_customer = 0;
            $logData = '关闭共享!';
        } else {
            $status = 1;
            $adminInfo->is_share_customer = 1;
            $logData = '开启共享!';
        }

        $adminInfo->save();
        $this->log("共享客户", $adminInfo, $logData);
        return $this->success(['status' => $status]);
    }

    public function getShareInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type' => [
                Rule::in([0, 1])
            ],//类型：0-供应商 1-客户
        ], [
            'type.in' => '参数`类型异常`丢失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $adminInfo = AdminAddendumModel::where('main_id', $this->getUserId())->first();
        if ($data['type']) {
            return $this->success($adminInfo['is_share_customer']);
        } else {
            return $this->success($adminInfo['is_set_as_supplier']);
        }
    }

    public function isSetAsSuppliers()
    {
        if ($this->getUserTpye()) {
            return $this->fail('', '当前账号权限不足，无法修改');
        }

        $adminInfo = AdminAddendumModel::where('main_id', $this->getUserId())->first();

        if ($adminInfo->is_set_as_supplier) {
            $status = 0;
            $adminInfo->is_set_as_supplier = 0;
            $logData = '关闭共享!';
        } else {
            $status = 1;
            $adminInfo->is_set_as_supplier = 1;
            $logData = '开启共享!';
        }

        $adminInfo->save();
        $this->log('共享供应商', $adminInfo, $logData);
        return $this->success(['status' => $status]);
    }

    /**
     * 开启体验
     * AUTHOR  : Sun Wu
     * DateTime: 2022/8/6 14:44
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function startToExperience()
    {
        if ($this->getUserId() != $this->getMainUserId()) {
            return $this->fail('', '子账号无权限开启，请联系主账号管理员！');
        }
        $adminInfo = AdminAddendumModel::where('main_id', $this->getUserId())->first();
        if ($adminInfo['is_end_experience']) {
            return $this->fail('', '您的体验资格已到期,感谢您的支持,付费后更精彩');
        }
        if (!empty($adminInfo['is_vip']) && time() > strtotime($adminInfo['vip_end_date'])) {
            return $this->fail('', '您已是VIP会员，无需开通0元体验！');
        }
        $logData = 'VIP体验已开启，感谢您的支持!';
        $this->operateLog('开启vip体验', $this->getUserId(), $this->time, $logData);
        if (!$adminInfo['is_in_experience'] && !$adminInfo['is_end_experience']) {
            $vipInfo = VipSettingModel::where('is_vip', 1)->first();

            $days = SystemConfigModel::where('key_value', 'experience_day')->first();

            $adminInfo->is_vip = 1;
            $adminInfo->vip_end_date = strtotime('+' . $days['value'] . ' day');
            $adminInfo->is_in_experience = 1;
            $adminInfo->album_amount = $vipInfo['album_amount'];
            $adminInfo->album_page_amount = $vipInfo['album_page_amount'];
            $adminInfo->empty_bill_amount = $vipInfo['empty_bill_amount'];
            $adminInfo->special_seal = $vipInfo['special_seal'];
            $adminInfo->one_key_album_times = $vipInfo['one_key_album_times'];
            $adminInfo->express_check_times = $vipInfo['express_check_times'];
            $adminInfo->account_storage = $vipInfo['account_storage'];
            $adminInfo->clear_watermark_or_not = $vipInfo['clear_watermark_or_not'];
            $adminInfo->save();
            $userInfo = AdminModel::query()->select(
                'username',
                'gz_openid'
            )->where(['id' => $this->getMainUserId()])->first();
            $mess = [
                'time' => Carbon::parse()->format('Y年m月d日'),
                'phone' => $userInfo['username'],
                'type' => 'VIP体验',
                'mark' => $days['value'] . '天VIP体验,开启成功!',
                'gz_openid' => $userInfo['gz_openid']
            ];
            //开启VIP体验，推送开启消息
            MessageService::buyerVipSpaceMessage($mess);
        }

        CommonService::operateResult($this->getUserId(), $this->time, ['code' => 0, 'msg' => 'success', 'data' => '']);
        return $this->success();
    }

    /**
     * 登陆后获取用户权限
     * Author: Sw
     * Created at 2023/2/23 9:42
     * @return \Illuminate\Http\JsonResponse
     */
    public function userPermissions()
    {
        if (!$this->getUserTpye()) {
            $result = AdminService::mainGetModelInfo($this->getMainUserId());
        } else {
            $result = AdminService::userGetModelInfo($this->getUserId());
        }

        return $this->success($result);
    }

    /**
     * 设置功能仅查看权限信息
     * Author: Sw
     * Created at 2023/2/21 17:03
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setPermissionLimit(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer|min:0',//用户id
            'module_info' => [
                'required',
                'json',
                new JsonArray([
                    'module_id' => 'required|integer',//模块id
                    'upper_module_id' => 'required|integer|',//模块上一级id
                ])
            ],
        ], [
            'id.required' => '参数`用户标识`丢失',
            'id.integer' => '参数`用户标识`仅能为整数',
            'id.min' => '参数`用户标识`最小只能为0',
            'module_info.required' => '参数`仅查看权限信息`丢失',
            'module_info.json' => '参数`仅查看权限信息`json数据格式错误'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        $this->log('设置子账号功能仅查看权限', $data);

        return response()->json(
            AdminService::setPermissionLimit($data)
        );
    }

    /**
     * 图片上传到oss系统
     * @param unknown $client
     * @param unknown $file
     */
    static public function addOssUploadImg($client, $mainId, $file, $path)
    {
        $res = handleUploadFileType($file);
        if (!empty($res)) return $res;
        $size = $file->getSize();
        $result = saveFileSize(['main_id' => $mainId], $size, $path);
        if ($result['code'] == 1) return $result;
        try {

            $fullPath = '/uploads/' . $path;
            $ossPath = ltrim($fullPath, './');
            $path = public_path() . $fullPath;
            $client->uploadFile(config('app.aliyun_oss_bucket'), $ossPath, $path);
            @unlink($path);
            $url = config('app.aliyun_oss_bucket_url') . $fullPath;
            return ["code" => 0, "msg" => "success", "data" => $url];

        } catch (\Exception $e) {

            return ["code" => 1, "msg" => "OSS系统，上传图片失败！", "data" => ""];
        }
    }

    /**
     * 处理图片和视频格式
     */
    static public function handlePicFormat($files, $flag, $msg)
    {
        $pic_format = 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp,avif,apng';
        $ext = $files->extension();
        $ext = strtolower($ext);
        if ($flag == 'p') {
            $pic_video_format_arr = explode(',', $pic_format);
        }
        if (!in_array($ext, $pic_video_format_arr)) {
            return ['code' => 1, 'msg' => $msg, 'data' => ''];
            die;
        }
    }

    /**
     * 选择用户列表
     * AUTHOR  : zlf
     * DateTime: 2023/10/31 16:07
     * @return \Illuminate\Http\JsonResponse
     */
    public function selUserList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ],
            [
                'pageSize.required' => '参数`pageSize`缺失',
                'pageSize.integer' => '参数`pageSize`只能为数字',
                'currentPage.required' => '参数`currentPage`缺失',
                'currentPage.integer' => '参数`currentPage`只能为数字',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info, 1);
        }
        $data['main_id'] = $this->getMainUserId();
        return $this->success(AdminService::selUserList($data));
    }

    /**
     * 微信绑定
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/10 11:07
     * @return \Illuminate\Http\JsonResponse
     */
    public function gzWechatBind(Request $request)
    {
        $adminInfo = AdminModel::where('id', $this->getUserId())->first();
        $gzInfo = json_decode(LoginService::getGzOpenId($request->code), true);
        $this->operateLog('公众号微信绑定', $this->getUserId(), $this->time);
        if (empty($adminInfo['gz_openid']) && !empty($request->code)) {
            $gzUserInfo = json_decode(LoginService::getGzUserInfo($gzInfo), true);
            AdminModel::where('id', $adminInfo['id'])->update([
                'openid' => $gzInfo['openid'],
                'wx_nickname' => $gzUserInfo['nickname']
            ]);
        }
        $logData = '微信绑定成功！';
        CommonService::operateResult($this->getUserId(), $this->time, ['code' => 0, 'msg' => 'success', 'data' => ''], $logData);
        return $this->success();
    }

    /**
     * 解绑微信
     * AUTHOR  : zlf
     * DateTime: 2023/12/2 11:01
     * @return \Illuminate\Http\JsonResponse
     */
    public function unbindGzWechat()
    {
        $adminInfo = AdminModel::where('id', $this->getUserId())->first();

        $this->operateLog('解绑公众号微信', $this->getUserId(), $this->time);
        if (!empty($adminInfo['gz_openid'])) {
            AdminModel::where('id', $this->getUserId())->update([
                'gz_openid' => '',
                'wx_nickname' => ''
            ]);
        } else {
            CommonService::operateResult($this->getUserId(), $this->time, ['code' => 1, 'msg' => '您当前还未绑定微信', 'data' => '']);
            return $this->fail('', '您当前还未绑定微信');
        }
        $logData = '解绑公众号成功！';
        CommonService::operateResult($this->getUserId(), $this->time, ['code' => 0, 'msg' => 'success', 'data' => ''], $logData);
        return $this->success();
    }

    public function editUserMenu(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'phone_menu' => 'nullable|json',//手机菜单数据
            'pc_menu' => 'nullable|json',//电脑菜单数据
        ],
            [
                'phone_menu.json' => '参数`手机菜单数据`为Json',
                'pc_menu.json' => '参数`电脑菜单数据`为Json',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $data['time'] = time();
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $this->operateLog('自定义菜单', $data, $data['time']);
        unset($data['main_id']);
        return Cache::lock(__CLASS__ . __FUNCTION__ . $data['user_id'], 5)
            ->get(function () use ($data) {
                // 锁定 10 秒并自动释放...
                return UserMenuService::edit($data);
            });
    }

    public function userMenuInfo(Request $request): JsonResponse
    {
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['user_type'] = $this->getUserTpye();
        //$data['is_vip'] = $this->isVip();
        return $this->success(UserMenuService::info($data));
    }

    public function getQrcode(Request $request)
    {
        if (Redis::get('qrcode_data'))
            $json = '{"expire_seconds": 604800, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": "smyc"}}}';
        $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
        $res = \App\V3\V3_2_7\Services\MessageService::qrcode($data);
        Redis::setex('qrcode_data', 7200, $res);
        if (!empty($res)) {
            $res = json_decode($res, true, 512, JSON_THROW_ON_ERROR);
            $res = file_get_contents('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $res['ticket']);
            return $res;
        } else {
            return $this->fail('', '数据异常');
        }
    }
}
